package com.superyee.commonlib.app;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.multidex.MultiDex;

import com.dueeeke.videoplayer.exo.ExoMediaPlayerFactory;
import com.dueeeke.videoplayer.player.VideoViewConfig;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.superyee.commonlib.constants.AppConfig;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;

public class BaseApplication extends Application {

    private static Context mAppContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();
        initSDk();
    }

    public static Context getAppContext() {
        return mAppContext;
    }

    private void initSDk() {
        // bugly 不要在异步线程初始化
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        boolean isMainProcess = processName == null || processName.equals(packageName);
        if (isMainProcess) {
            VideoViewManager.setConfig(VideoViewConfig.newBuilder()
                    //使用使用IjkPlayer解码  3.2.1版本在小米9手机上面运行异常
//                    .setPlayerFactory(IjkPlayerFactory.create())
                    //使用ExoPlayer解码
                    .setPlayerFactory(ExoMediaPlayerFactory.create())
                    //使用MediaPlayer解码
//                    .setPlayerFactory(AndroidMediaPlayerFactory.create())
                    .build());
        }
        strategy.setUploadProcess(isMainProcess);
        // 初始化Bugly
        if (!AppConfig.DEBUG) {
            CrashReport.initCrashReport(context, AppConfig.BUGLY_APPID, AppConfig.DEBUG, strategy);
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }


}
